// 请求拦截器
import Request from "./request";
import type { RequestConfig, Response } from "./types";

const Api = new Request();

// 请求拦截器
Api.interceptors.request((request: RequestConfig) => {
    const token = uni.getStorageSync("token") || "";

    // 初始化 header 对象（如果不存在）
    if (!request.header) {
        request.header = {};
    }

    // 加载处理
    if (request.loading) {
        uni.showLoading({
            title: "请稍等...",
            mask: false
        });
    }

    // 请求头处理
    if (token) {
        request.header["Authorization"] = "Bearer " + token;
    }
    request.header["tenant-id"] = "1";

    // 处理 params 参数
    if (request.params) {
        request.header["Content-Type"] = "application/x-www-form-urlencoded";
        request.data = request.params;
        delete request.params;
    } else {
        request.header["Content-Type"] = "application/json";
    }

    // 初始化 data 对象（如果不存在）
    if (!request.data) {
        request.data = {};
    }

    // 空值处理
    for (const key in request.data) {
        if (Object.prototype.hasOwnProperty.call(request.data, key)) {
            const value = request.data[key];
            if (value === null || value === undefined || value === "") {
                delete request.data[key];
            }
        }
    }

    return request;
});

// 响应拦截器
Api.interceptors.response(async (response: Response, options: RequestConfig) => {
    // 调试日志
    console.log(options.apiName, {
        请求参数: { ...options.data },
        响应参数: {
            code: response.data?.code,
            data: response.data?.data
        }
    });

    // 隐藏加载提示
    uni.hideLoading();

    const statusCode = response.data?.code;
    console.log("response.data", response.data);

    // 响应头处理，刷新token
    // if (response.header?.Authorization) {
    //   uni.setStorageSync('token', response.header.Authorization)
    // }

    // 根据状态码处理响应
    switch (statusCode) {
        case 200:
        case 0:
            return response.data;
        case 400:
            uni.showToast({
                title: response.data?.msg || "请求参数错误",
                icon: "none",
                duration: 2000
            });
            return response.data;
        case 401:
        case 403:
            uni.showToast({
                title: response.data?.msg || "未授权或无权限",
                icon: "none",
                duration: 2000
            });
            // 可以在这里添加跳转到登录页的逻辑
            // uni.navigateTo({ url: '/pages/login/login' })
            return response.data;

        default:
            const errorMsg = response.data?.msg || `[${options.apiName || "接口"}错误]`;
            console.error(`[${options.apiName || "接口"}错误]`, {
                code: response.statusCode,
                data: response.data
            });
            uni.showToast({
                title: errorMsg,
                icon: "none",
                duration: 2000
            });
            return response.data;
    }
});

export default Api;
